<template>
  <div class="map-search">
    <van-search
      id="searchInput"
      v-model.trim="searchValue"
      show-action
      shape="round"
      autocomplete="country-name"
      placeholder="请输入搜索地址关键字"
      @update:model-value="onSearch"
    >
      <template #action>
        <div class="map-search_btn" @click.stop="onClickButton">搜索</div>
      </template>
    </van-search>

    <!-- <van-popover :show="showPopover" :actions="addressList" /> -->
  </div>
  <div id="map" />

  <van-popup
    v-model:show="showPopover"
    round
    position="bottom"
    :style="{ height: '50%' }"
    :overlay="false"
  >
    <div v-if="selectActions.length" class="map-search_actions">
      <div
        v-for="(item, idx) of selectActions"
        :key="idx"
        class="actions-item"
        @click.stop="select(item)"
      >
        <van-icon name="search" />
        <span
          v-show="item.business"
          :class="[{ 'actions-item_business': item.business }]"
          >{{ item.business }}</span
        >
        <span
          :class="['actions-item_address', { 'has-business': item.business }]"
          >{{ item.address }}</span
        >
      </div>
    </div>
  </van-popup>
</template>

<script lang="ts" setup name="KAMap">
import { ref, onMounted, reactive, computed, nextTick, watchEffect } from 'vue'
interface AutocompleteResultType {
  business: string
  city: string
  district: string
  province: string
  street: string
  streetNumber: string
  address?: string
}

interface OnSearchComplete {
  getNumPois: () => number
  getPoi: () => AutocompleteResultType[]
}
const searchValue = ref('')
const showResultFlag = ref(false)

const mapRef = ref()
const searchResult = ref<any[]>([])
const selectInfo = reactive({
  lng: 0,
  lat: 0,
  addressStr: '',
  title: '',
  province: '', // 省
  city: '', // 市
  district: '', // 区
})

const addressList = ref<AutocompleteResultType[]>([])
const showPopover = ref(false)

const selectActions = computed(() => {
  return addressList.value
    .map((_value) => {
      return {
        ..._value,
        address:
          _value.province +
          _value.city +
          _value.district +
          _value.street +
          _value.streetNumber,
      }
    })
    .filter((v) => v.address || v.business)
})

watchEffect(() => (showPopover.value = !!searchValue.value))

const initMap = async () => {
  await nextTick()
  mapRef.value = new window.BMapGL.Map('map')
  // 设置中心点坐标和地图级别 默认是北京
  mapRef.value.centerAndZoom(new window.BMapGL.Point(116.404, 39.915), 12)

  // 添加缩放控件
  mapRef.value.addControl(new window.BMapGL.ZoomControl())

  // 建立一个自动完成的对象 用于模糊搜索
  const acMap = new window.BMapGL.Autocomplete({
    input: 'searchInput',
    location: mapRef.value,
    onSearchComplete: (val: OnSearchComplete) => {
      addressList.value = []
      const addrNums = val.getNumPois()
      for (let index = 0; index < addrNums; index++) {
        const ele = val.getPoi(index)

        ele && addressList.value.push(ele)
      }
    },
  })
  acMap.addEventListener('click', function (e) {
    mapRef.value.clearOverlays()

    console.log('点击坐标： ', e.point.lng + ',' + e.point.lat)
  })

  acMap.addEventListener('onconfirm', function (e, target, item) {
    console.log('onconfirm:', e, target, item)
    //鼠标点击下拉列表后的事件
    const _value = e.item.value
    const myValue =
      _value.province +
      _value.city +
      _value.district +
      _value.street +
      _value.streetNumber +
      _value.business
    console.log('选取的地址：', myValue)
    getPlaceGeoOfBMapGL(myValue)
  })
}

// 获取某个地点的经纬度
function getPlaceGeoOfBMapGL(value: string) {
  const local = new window.BMapGL.LocalSearch(mapRef.value, {
    //智能搜索
    onSearchComplete: function () {
      const geo = local.getResults().getPoi(0).point
      console.log('当前选取地址的经纬度： ', geo.lng, +geo.lat)
      mapRef.value.centerAndZoom(geo, 18)
      mapRef.value.addOverlay(new window.BMapGL.Marker(geo))
    },
  })
  local.search(value)
}
const onSearch = () => {
  console.log('onSearch ==> :')
}
const select = (item: AutocompleteResultType) => {
  const _address = item.business + item.address
  getPlaceGeoOfBMapGL(_address)
  // searchValue.value = ''
}

const onClickButton = () => {
  //
}

onMounted(async () => {
  initMap()
})
</script>

<style lang="scss">
.map-search {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  margin-bottom: 55px;
  font-size: 13px;

  &_btn {
    width: 46px;
    color: #fff;
    text-align: center;
    background: #01abfe;
    border-radius: 13px;
  }
}

#map {
  width: 300px;
  height: 100%;
  overflow-y: auto;
}
</style>
